<?php

namespace app\admin\controller\org;

use app\common\controller\Backend;
use fast\Tree;
/**
 * 
 *
 * @icon fa fa-file
 */
class Org extends Backend
{
    
    /**
     * Org模型对象
     */
    protected $model = null;
    protected $noNeedRight=[];
    protected $noNeedLogin=[];


    public function _initialize()
    {
        parent::_initialize();
        $this->shopid=false;
        $this->model = model('Org');
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where);
            if ($_SESSION['think']['admin']['group_id'] == 2) {
                $total = $total->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }
            $total = $total
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where);
            if ($_SESSION['think']['admin']['group_id'] == 2) {
                $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }
            $list = $list->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            //$this->model->getLastSql();
            $list = collection($list)->toArray();
            for($i=0;$i<count($list);$i++){
                $list[$i]['city_id']=$this->model->getCity_idTextAttr($list[$i]['city_id'],$list[$i]);
                $list[$i]['area_id']=$this->model->getArea_idTextAttr($list[$i]['area_id'],$list[$i]);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        $this->assign("user_type",$_SESSION['think']['admin']['group_id']);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['create_time']=$datatime;
                    if($_SESSION['think']['admin']['group_id']==2){
                        $params['city_id']=$_SESSION['think']['admin']['city_id'];
                    }
                    unset($params['delete_time']);
                    unset($params['update_time']);
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign("user_type",$_SESSION['think']['admin']['group_id']);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['update_time']=$datatime;
                    unset($params['delete_time']);
                    unset($params['create_time']);
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign("user_type",$_SESSION['think']['admin']['group_id']);
        $this->view->assign("row", $row);
        return $this->view->fetch();

    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row=$this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL){
        $where="where 1=1";
        if($_SESSION['think']['admin']['group_id']!=1){
            $where.=" and city_id='{$_SESSION['think']['admin']['city_id']}'";
        }
        $page=1;
        $pagesize=50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn=preg_split("/\,/",$keyValue);
                    for($i=0;$i<count($nn);$i++) {
                        $where.= " and $keyField='{$nn[$i]}'";
                    }
                }
            }
        }
        $sql="select id,name name from __prefix__fa_org $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

        //$tree = Tree::instance();
        //$tree->init($list, 'pid');
        //if(isset($keyValue)&&$keyValue!=""){
        //}else{
        //    $list=$tree->getTreeList($tree->getTreeArray(0), 'name');
        //    //array_unshift($list,array("name"=>"无父级","pid"=>0,"weigh"=>9999));
        //}

        $total = db()->query("select count(1) as c from  __prefix__fa_org $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

}
